package repository

import (
	"context"
	"go-pan/internal/model"
	"gorm.io/gorm"
)

type UploadTaskRepository interface {
	Create(ctx context.Context, task *model.UploadTask) error
	FindByID(ctx context.Context, id int64) (*model.UploadTask, error)
	FindByUploadID(ctx context.Context, uploadID int64) (*model.UploadTask, error)
	Update(ctx context.Context, task *model.UploadTask) error
}

type UploadTaskRepositoryImpl struct {
	db *gorm.DB
}

func NewUploadTaskRepository(db *gorm.DB) *UploadTaskRepositoryImpl {
	return &UploadTaskRepositoryImpl{db: db}
}

func (r *UploadTaskRepositoryImpl) Create(ctx context.Context, task *model.UploadTask) error {
	return r.db.WithContext(ctx).Create(task).Error
}

func (r *UploadTaskRepositoryImpl) FindByID(ctx context.Context, id int64) (*model.UploadTask, error) {
	var task model.UploadTask
	if err := r.db.WithContext(ctx).First(&task, id).Error; err != nil {
		return nil, err
	}
	return &task, nil
}

func (r *UploadTaskRepositoryImpl) FindByUploadID(ctx context.Context, uploadID int64) (*model.UploadTask, error) {
	var task model.UploadTask
	// upload_id 是主键，直接使用 First 查找
	if err := r.db.WithContext(ctx).First(&task, uploadID).Error; err != nil {
		return nil, err
	}
	return &task, nil
}

func (r *UploadTaskRepositoryImpl) Update(ctx context.Context, task *model.UploadTask) error {
	return r.db.WithContext(ctx).Save(task).Error
}
